package com.yiyw.herostory.handler;

import com.yiyw.herostory.bo.UserBo;
import com.yiyw.herostory.manage.ChannelGroupManage;
import com.yiyw.herostory.manage.UserManage;
import com.yiyw.herostory.proto.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author yiyw
 * @Description 用户攻击事件
 * @Date 2022/8/15 22:53
 **/
@Slf4j
public class UserAttkCmdHandler implements ICmdHandler<GameMsgProtocol.UserAttkCmd> {

    @Override
    public void handler(ChannelHandlerContext ctx, GameMsgProtocol.UserAttkCmd msg) {
        int targetUserId = msg.getTargetUserId();

        // 攻击事件
        GameMsgProtocol.UserAttkResult.Builder result = GameMsgProtocol.UserAttkResult.newBuilder();
        result.setAttkUserId(ChannelGroupManage.getUserIdByChannel(ctx.channel()));
        result.setTargetUserId(targetUserId);

        // 被攻击者减血
        GameMsgProtocol.UserSubtractHpResult.Builder userSubtractHpResult = GameMsgProtocol.UserSubtractHpResult.newBuilder();
        userSubtractHpResult.setSubtractHp(10);
        userSubtractHpResult.setTargetUserId(targetUserId);

        ChannelGroupManage.writeAndFlush(result.build());
        ChannelGroupManage.writeAndFlush(userSubtractHpResult.build());

        // 计算被攻击者是否死亡
        UserBo targetUser = UserManage.getUser(targetUserId);
        if (targetUser == null) {
            return;
        }
        int hp = targetUser.subUserHp(10);
        log.info("curr thread: {}, targetUserId: {}, hp: {}", Thread.currentThread().getName(), targetUserId, hp);
        if (hp <= 0) {
            // 玩家死亡
            GameMsgProtocol.UserDieResult.Builder userDie = GameMsgProtocol.UserDieResult.newBuilder();
            userDie.setTargetUserId(targetUserId);
            ChannelGroupManage.writeAndFlush(userDie.build());
        }

    }
}
